<?php

namespace App\Repository;

use App\Exceptions\BusinessException;
use App\Common\Constant;
use App\Common\ResponseCode;
use App\Models\Base\Files;
use App\Models\Customer\Address;
use App\Models\Customer\Customer;
use App\Models\Goods\AttributesValue;
use App\Models\Goods\FileBind;
use App\Models\Goods\Goods;
use App\Models\Goods\Products;
use App\Models\Role\Role;
use App\Models\User\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 * 收货地址数据仓储类
 *
 * @package App\Http\Repository
 * @author WangBin
 * @mail: <849850352@qq.com>
 */
class AddressRepository extends BaseRepository
{
    /**
     * 保存数据
     *
     * @param array $data
     * @param int $addressId
     * @throws
     * @return int|mixed
     */
    public function save(array $data, int $addressId = 0)
    {
        try {
            $query = $addressId ? Address::find($addressId) : new Address();
            collect($data)->each(function ($value, $field) use ($query) {
                $query->{$field} = $value;
            });
            return $query->save() ? $query->address_id : 0;
        } catch (\Exception $exception) {
            Log::error("[收货地址] 保存失败：{$exception->getMessage()}");
            throw new BusinessException(ResponseCode::SAVE_FAIL);
        }
    }

    /**
     * 获取客户收货地址
     *
     * @param int $customerId
     * @param bool $default
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     */
    public function getByCustomerId(int $customerId, $default = false)
    {
        $query = Address::query()->where('customer_id', $customerId);
        if($default) {
            $query->where('is_default', $default);
        }
        return $query->first();
    }

    /**
     * 收货地址列表
     *
     * @param array $filter
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function getList(array $filter = [])
    {
        $query = Address::query()->orderByDesc('created_at');
        if(!empty($filter['customer_id'])) {
            $query->where('customer_id', $filter['customer_id']);
        }
        if(!empty($filter['customer_name'])) {
            $query->where('customer_name', 'like', '%' . $filter['customer_name'] . '%');
        }
        if(!empty($filter['group_id'])) {
            $customerIds = Customer::query()->where('group_id', $filter['group_id'])->select('customer_id')->get()->values();
            $query->whereIn('customer_id', $customerIds);
        }
        return $query;
    }

    /**
     * 获取收货地址
     *
     * @param int $addressId
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     */
    public function getById(int $addressId)
    {
        $query = Address::query()->where('address_id', $addressId)->first();
        $query->regions = ['region_id' => explode('/', $query->region_id), 'region' => explode('/', $query->region)];
        return $query;
    }

    /**
     * 设置默认地址
     *
     * @param int $addressId
     * @param int $customerId
     * @return bool
     */
    public function setDefault(int $addressId, int $customerId)
    {
        $result = false;
        try {
            DB::beginTransaction();
            Address::query()->where('customer_id', $customerId)->update(['is_default' => 0]);
            Address::query()->where('address_id', $addressId)->update(['is_default' => 1]);
            DB::commit();
            $result = true;
        } catch (\Exception $exception) {
            DB::rollBack();
            Log::error("[设置默认地址] 出错：{$exception->getMessage()}");
        }
        return $result;
    }
}
